package com.changgou.web.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.CartFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.AddressFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@CrossOrigin
@RequestMapping("/worder")
public class OrderController {
    @Autowired
    private AddressFeign addressFeign;
    @Autowired
    private CartFeign cartFeign;
    @Autowired
    private OrderFeign orderFeign;

    @RequestMapping("/ready/order")
    public String readyOrder(Model model) {
        List<Address> addressList = addressFeign.list().getData();
        model.addAttribute("address", addressList);
        Map map = cartFeign.list();
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");
        model.addAttribute("order", orderItemList);
        Integer totalMoney = (Integer) map.get("totalMoney");
        model.addAttribute("totalMoney", totalMoney);
        Integer totalNum = (Integer) map.get("totalNum");
        model.addAttribute("totalNum", totalNum);
        List<Address> collect = addressList.stream()
                .filter(address -> address.getIsDefault().equals("1")).collect(Collectors.toList());
        model.addAttribute("deAddr", collect.get(0));
        return "order";
    }

    /***
     * 添加订单数据到购物车中
     * @param order
     * @return
     */
    @PostMapping(value = "/add")
    @ResponseBody
    public Result add(@RequestBody Order order) {
        Result result = orderFeign.add(order);
        return result;
    }

}
